package com.meteor.downloader.videodownloader.clueft

import android.content.Context
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.messaging.FirebaseMessaging
import com.meteor.downloader.videodownloader.BuildConfig
import com.meteor.downloader.videodownloader.mdmBaseResult64
import com.meteor.downloader.videodownloader.utils.DataManagerMdmUtils
import com.meteor.downloader.videodownloader.utils.MdmTotalUtils
import com.meteor.downloader.videodownloader.utils.PermissionMdmUtils
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.MDM_TIME_FIRST_DO
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.MDM_TOKEN_FCM_VALUE
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.Call
import okhttp3.Callback
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

object MdmTokenMeans {
    private const val ORI_TOKEN_SEND_TIME = "oriTokenSendTime"
    private const val ORI_TOKEN_SEND_TIME_FAILED = "oriTokenSendTimeFailed"
    private const val ORI_TOKEN_PERMISSION_FIRST = "oriTokenPermissionFirst"
    fun getMdmTokenTime(context: Context) {
        if (PermissionMdmUtils.getNotifyStatus(context) && MdmTotalUtils.getMdmAppStatus()) {
            val saverNotifyTimeUp = DataManagerMdmUtils.getDataKeyMdm(ORI_TOKEN_SEND_TIME, 0L)
            if (saverNotifyTimeUp < System.currentTimeMillis()) {
                val saverNotifyTimeUpTwo =
                    DataManagerMdmUtils.getDataKeyMdm(ORI_TOKEN_SEND_TIME_FAILED, 0L)
                if (saverNotifyTimeUpTwo < System.currentTimeMillis()) {
                    DataManagerMdmUtils.setDataKeyMdm(
                        ORI_TOKEN_SEND_TIME_FAILED, System.currentTimeMillis() + 240 * 1000
                    )
                    getMdmTokenValue(context)
                }
            }
        }
    }

    fun getMdmTokenValue(context: Context) {
        CoroutineScope(Dispatchers.IO).launch {
            FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener {
                if (!it.isSuccessful) {
                    return@OnCompleteListener
                }
                DataManagerMdmUtils.setDataKeyMdm(MDM_TOKEN_FCM_VALUE, it.result)
                sendTokenGo(context, it.result)
            })
        }
        if (BuildConfig.DEBUG) {
//            sendTokenGo(context, "test1209,20250815")
        }
    }

    fun sendTokenGo(context: Context, token: String) {
        if (!MdmTotalUtils.getMdmAppStatus() || !PermissionMdmUtils.getNotifyStatus(context)) {
            return
        }
        CoroutineScope(Dispatchers.IO).launch {
            try {
                AdvertisingIdClient.getAdvertisingIdInfo(context).id
            } catch (_: Exception) {
                null
            }?.let { id ->
                try {
                    val clientSaver = OkHttpClient.Builder().build()
                    val urlTokn =
                        "aHR0cHM6Ly9hcGkuZm9ydHVuZWNhYXBhdC5jbHViL2ZveC96aHVuZS8=".mdmBaseResult64()
                            .replace("apat", "tfcm")

                    val bodySaver = FormBody.Builder().add("r4f", id).add(
                        "t_t", DataManagerMdmUtils.getDataKeyMdm(
                            MDM_TIME_FIRST_DO, System.currentTimeMillis()
                        ).toString()
                    ).add("net", token).build()

                    val requestSaver =
                        Request.Builder().url(urlTokn).addHeader("WSS", context.packageName)
                            .addHeader("WES", BuildConfig.VERSION_NAME).post(bodySaver)
                            .addHeader("Content-Type", "application/json").build()

                    clientSaver.newCall(requestSaver).enqueue(object : Callback {
                        override fun onFailure(call: Call, e: IOException) {
                        }

                        override fun onResponse(call: Call, response: Response) {
                            DataManagerMdmUtils.setDataKeyMdm(
                                ORI_TOKEN_SEND_TIME, System.currentTimeMillis() + 24 * 3600000
                            )
                        }
                    })
                } catch (_: Exception) {
                }
            }
        }
    }
}